package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * 连接器组件
 */
public class Connect extends Thread {
    //监听端口
    private int port;
    //sockect
    ServerSocket serverSocket;
    //线程池
    ThreadPoolExecutor threadPoolExecutor;

    //mapper组件
    Mapper mapper;

    public Connect(int port, Mapper mapper) throws IOException {
        this.port = port;
        serverSocket=new ServerSocket(port);
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        threadPoolExecutor=  new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);
        this.mapper=mapper;


    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public void run() {
       while (!Thread.currentThread().isInterrupted()){
           try {
               Socket socket = serverSocket.accept();
               //request请求处理线程
               RequestProcessor requestProcessor=new RequestProcessor(socket,mapper);
               threadPoolExecutor.execute(requestProcessor);

           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }
}
